package com.example.common.jwt;


import cn.hutool.core.date.DateTime;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class JwtUtils {
    private static final String SECRET_KEY = "secretKey:123456";
    // 过期时间
    public static final long TOKEN_EXPIRE_TIME = 7200 * 1000;

    public static String createJwt(UserMsg userMsg) {
        LocalDateTime expiration = LocalDateTime.now().plusSeconds(TOKEN_EXPIRE_TIME);
        String jwtString = Jwts.builder()
                .claim("id", userMsg.getId())
                .claim("userName", userMsg.getUserName())
                .claim("role", userMsg.getUserRole())
                .setExpiration(Date.from(expiration.atZone(ZoneId.systemDefault()).toInstant()))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
        return jwtString;
    }

    public static Jws<Claims> parserToken(String token) {
        return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
    }
}
